package cc.rengu.redp.bizimpl.igas.service.impl;

import cc.rengu.redp.bizimpl.enums.IgasYesOrNoEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.enums.SettleAccTypeEnum;
import cc.rengu.redp.bizimpl.igas.dao.PDstChannelInfoMapper;
import cc.rengu.redp.bizimpl.igas.domain.PDstChannelInfo;
import cc.rengu.redp.bizimpl.igas.service.PDstChannelInfoService;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpPrivilegeCheckService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.DateUtil;
import cc.rengu.redp.common.utils.SortUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 刘玉亮.LL
 * @since 2021-06-08
 */
@DS("igas")
@Service
public class PDstChannelInfoServiceImpl extends ServiceImpl<PDstChannelInfoMapper, PDstChannelInfo> implements PDstChannelInfoService {
    @Autowired
    private IUpmpPrivilegeCheckService privilegeCheckService;
    @Autowired
    private  PDstChannelInfoService pDstChannelInfoService;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    private String oprMenuId = "20000014";
    private String oprMenuName = "产品管理:支付通道管理";
    private String oprBtnNamePrefix = "支付通道管理";
    private String webNextUrl = "/admin/igas/pSrcChannelInfo/edit";

    @Override
    public String getOprMenuName() {
        return oprMenuName;
    }

    @Override
    public String getOprMenuId() {
        return oprMenuId;
    }

    @Override
    public PDstChannelInfo findOne(String instId, String dstChannelId) throws RedpException {
        PDstChannelInfo pDstChannelInfo;

        StringBuffer param1 = new StringBuffer();

        if (Common.isNotBlank(instId)) {
            param1.append(" INST_ID = :instId");
        } else {
            throw new RedpException("查询支付通道信息唯一索引列[instId]条件为空");
        }
        if (!Common.isBlank(dstChannelId)) {
            if (Common.isBlank(param1))
                param1.append(" DST_CHANNEL_ID =:dstChannelId ");
            else
                param1.append(" and DST_CHANNEL_ID =:dstChannelId ");
        } else {
            throw new RedpException("查询支付通道信息唯一索引列[dstChannelId]条件为空");
        }
        QueryWrapper<PDstChannelInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("INST_ID" ,instId);
        queryWrapper.eq("DST_CHANNEL_ID", dstChannelId);
        return pDstChannelInfoService.getOne(queryWrapper);
    }



    @Override
    public IPage<PDstChannelInfo> findByPage(QueryRequest request, PDstChannelInfo info) {
        try {
            LambdaQueryWrapper<PDstChannelInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isNotBlank(info.getInstId())) {
                queryWrapper.eq(PDstChannelInfo::getInstId, info.getInstId());
            } else {
                //获取当前用户的法人id
                UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                queryWrapper.eq(PDstChannelInfo::getInstId, user.getInstId());
            }
            if (StringUtils.isNotBlank(info.getDstChannelId())) {
                queryWrapper.like(PDstChannelInfo::getDstChannelId, info.getDstChannelId());
            }
            queryWrapper.orderByDesc(PDstChannelInfo::getDstChannelName);
            Page<PDstChannelInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            Page<PDstChannelInfo> idPDstChannelInfo = this.page(page, queryWrapper);
           if (idPDstChannelInfo.getTotal()==0){
               LambdaQueryWrapper<PDstChannelInfo> queryWrapper1 = new LambdaQueryWrapper<>();
               if (StringUtils.isNotBlank(info.getInstId())) {
                   queryWrapper1.eq(PDstChannelInfo::getInstId, info.getInstId());
               } else {
                   //获取当前用户的法人id
                   UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                   queryWrapper1.eq(PDstChannelInfo::getInstId, user.getInstId());
               }
               queryWrapper1.like(PDstChannelInfo::getDstChannelName, info.getDstChannelId());
               queryWrapper1.orderByDesc(PDstChannelInfo::getDstChannelName);
               idPDstChannelInfo = this.page(page, queryWrapper1);
           }
            return idPDstChannelInfo;
        } catch (Exception e) {
            log.error("查询失败", e);
            return null;
        }
    }

    @Override
    @Transactional
    public void update(PDstChannelInfo entity) throws RedpException {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);
        entity.setUpdateTime(lastUpddt);
        LambdaQueryWrapper<PDstChannelInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PDstChannelInfo::getInstId, entity.getInstId());
        wrapper.eq(PDstChannelInfo::getDstChannelId, entity.getDstChannelId());
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(entity.getOptFlag()) || PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(entity.getOptFlag())) {

           /* UpmpPrivilegeCheck privilegeCheck = privilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), oprBtnNamePrefix + BusinessContainer.AUTH_PRIVILEGE_CODE_SPLIT + PageOptFlagEnum.OPT_FLAG_UPDATE.getDesc());
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                log.error("不支持审核操作!");
                throw new RedpException("不支持审核操作！");
            } else {*/
                // 修改
//            QueryWrapper<PDstChannelInfo> queryWrapper=new QueryWrapper<>();
                PDstChannelInfo pDstChannelInfo = this.getOne(wrapper);
                if (!IgasYesOrNoEnum.Yes.getType().equals(entity.getBizTimeFlag()) && StringUtils.isNotBlank(entity.getSupportAcctType())) {
                    if (!entity.getSupportAcctType().equals("*"))
                    entity.setSupportAcctType(getSupportAcctType(entity.getSupportAcctType()));
                }
            if (!IgasYesOrNoEnum.Yes.getType().equals(entity.getBizTimeFlag())) {
                    BeanUtils.copyProperties(entity,pDstChannelInfo);
                } else {

                    pDstChannelInfo.setBizCtrlRule( entity.getBizCtrlRule());
                    pDstChannelInfo.setBizStartDate(entity.getBizStartDate());
                    pDstChannelInfo.setBizStartTime(entity.getBizStartTime());
                    pDstChannelInfo.setBizEndTime(entity.getBizEndTime());
                    pDstChannelInfo.setChannelTimeout(entity.getChannelTimeout());
                    pDstChannelInfo.setUpdateTime(lastUpddt);

                }
                this.baseMapper.update(pDstChannelInfo, wrapper);

           /* }*/
        } else if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(entity.getOptFlag())
                || PageOptFlagEnum.OPT_FLAG_USE.getType().equals(entity.getOptFlag())
                || PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(entity.getOptFlag())) {
            UpmpPrivilegeCheck privilegeCheck;
            if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(entity.getOptFlag())) {
               /* privilegeCheck = privilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), oprBtnNamePrefix + BusinessContainer.AUTH_PRIVILEGE_CODE_SPLIT + PageOptFlagEnum.OPT_FLAG_STOP.getDesc());
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    log.error("不支持审核操作!");
                    throw new RedpException("不支持审核操作！");
                } else {*/
                    entity.setDstChannelStatus(IgasYesOrNoEnum.No.getType());
               /* }*/
            } else if (PageOptFlagEnum.OPT_FLAG_USE.getType().equals(entity.getOptFlag())) {
                /*privilegeCheck = privilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), oprBtnNamePrefix + BusinessContainer.AUTH_PRIVILEGE_CODE_SPLIT + PageOptFlagEnum.OPT_FLAG_USE.getDesc());
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    log.error("不支持审核操作!");
                    throw new RedpException("不支持审核操作！");
                } else {*/
                    entity.setDstChannelStatus(IgasYesOrNoEnum.Yes.getType());
             /*   }*/
            } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(entity.getOptFlag())) {
               /* privilegeCheck = privilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), oprBtnNamePrefix + BusinessContainer.AUTH_PRIVILEGE_CODE_SPLIT + PageOptFlagEnum.OPT_FLAG_CANCEL.getDesc());
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    log.error("不支持审核操作!");
                    throw new RedpException("不支持审核操作！");
                } else {*/
                    entity.setDstChannelStatus(IgasYesOrNoEnum.No.getType());
               /* }*/
            }
            this.baseMapper.update(entity, wrapper);
        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(entity.getOptFlag())) {
            log.error("不支持审核操作!");
            throw new RedpException("不支持审核操作！");
        }
    }

    /**
     * 将界面传回的PDstChannelInfo对象的 supportAcctType 字段根据表字段说明做转换
     *
     * @param pageAccType
     * @return
     */
    @Override
    public String getSupportAcctType(String pageAccType) {
        if (SettleAccTypeEnum.ALL_ACCOUNT.getType().equals(pageAccType)) {
            return pageAccType;
        }
        StringBuffer supportAcctType = new StringBuffer();
        SettleAccTypeEnum[] sets = SettleAccTypeEnum.values();
        for (int i = 0; i < 10; i++) {//通道支持的账户类型目前就前面10个，后面根据需要放开
            SettleAccTypeEnum set = sets[i];
            if (pageAccType.indexOf(set.getType()) >= 0)
                supportAcctType.append(IgasYesOrNoEnum.Yes.getType());
            else
                supportAcctType.append(IgasYesOrNoEnum.No.getType());

        }

        return supportAcctType.toString();
    }

}
